package com.atguigu.yygh.common.result;

import io.swagger.annotations.ApiModelProperty;
import lombok.Getter;
import lombok.Setter;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @Author 孔德成
 * @Slogan 致敬大师，致敬未来的你
 * @date 2021/8/28
 */
@Getter
@Setter
public class R {
    @ApiModelProperty(value = "是否成功")
    private Boolean success;
    @ApiModelProperty(value = "返回码")
    private Integer code;
    @ApiModelProperty(value = "返回消息")
    private String message;
    @ApiModelProperty(value = "返回数据")
    private Map<String, Object> data = new HashMap<>();

    private R() {
    }

    private R(Boolean success, Integer code, String message) {
        this.success = success;
        this.code = code;
        this.message = message;
    }

    private R(Boolean success, Integer code, String message, Map<String, Object> data) {
        this(success, code, message);
        this.data = data;
    }

    public static R ok() {
        return new R(true, ResultCode.SUCCESS, "成功");
    }

    public static R error() {
        return new R(false, ResultCode.ERROR, "失败");
    }

    public static R error(Integer code, String message) {
        return new R(false, code, message);
    }


    public R success(Boolean success) {
        this.success = success;
        return this;
    }

    public R message(String message) {
        this.message = message;
        return this;
    }

    public R code(Integer code) {
        this.code = code;
        return this;
    }

    /**
     * 通用的添加数据方法
     */
    public R data(String key, Object value) {
        this.data.put(key, value);
        return this;
    }

    public R data(Map<String, Object> map) {
        this.data = map;
        return this;
    }

    /**
     * 返回列表数据
     *
     * @param list
     * @return
     */
    public R data(List list) {
        this.data("items", list);
        return this;
    }

    /**
     * 返回分页数据
     *
     * @param total 总数
     * @param rows  数据列表
     * @return
     */
    public R data(Long total, List rows) {
        this.data("total", total).data("rows", rows);
        return this;
    }

}
